package com.laxcen.basiclib.utils;

import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;

import com.laxcen.basiclib.BaseApp;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

/**
 *  统一文件系统
 *  文件开头以 file:// 开头
 *  实际存储在APP私用目录
 */
public class FileUtil {

    //APP文件存储跟目录
    public static String parentStoragePath = BaseApp.getApp().getFilesDir().getAbsolutePath();
    //新H5版本路径
    public static String newH5VersionPath ;

    /**
     * 获取系统下载目录路径
     * @return
     */
    public static String getDownloadPath(){
        String path = Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_DOWNLOADS) +BaseApp.getApp().getPackageName();
        File file = new File(path);
        if(!file.exists()){
            file.mkdirs();
        }
        return path;
    }
    /**
     * 删除文件
     *
     * @param fileName
     * @return
     */
    public static boolean deleteFile(String fileName) {
        boolean status;
        SecurityManager checker = new SecurityManager();
        File file = new File(parentStoragePath + fileName);
        if (file.exists()){
            checker.checkDelete(file.toString());
            if (file.isFile()) {
                try {
                    file.delete();
                    status = true;
                } catch (SecurityException se) {
                    se.printStackTrace();
                    status = false;
                }
            } else
                status = false;
        }else
            status = false;
        return status;
    }

    /**
     *  获取 新H5版本路径
     * @return
     */
    public static String getNewH5VersionPath(){
        newH5VersionPath = parentStoragePath+"/newH5VersionPath/";
        File f = new File(newH5VersionPath);
        if(!f.exists()){
            f.mkdir();
        }
        return newH5VersionPath;
    }

    /**
     * 获取文件根目录
     * @return
     */
    public static String getFilePath(){
        return parentStoragePath+"/file";
    }

    /**
     *  以字符为单位读取文件，常用于读取文本文件
     * @param path
     * @return
     */
    public static String readFile(String path) {
        String content = null;
        try {
            Reader reader = new InputStreamReader(new FileInputStream(path), "utf-8");
            StringBuffer sb = new StringBuffer();
            char[] tempchars = new char[1024];
            while (reader.read(tempchars) != -1) {
                sb.append(tempchars);
            }
            content = sb.toString();
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return content;
    }

    /**
     *  把内容content写的path文件中
     * @param content
     * @param path
     * @return
     */
    public static boolean saveFile(String content, String path) {
        FileWriter fw = null;
        try {
            fw = new FileWriter(new File(path), false);
            if (content != null) {
                fw.write(content);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } finally {
            if (fw != null) {
                try {
                    fw.flush();
                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return true;
    }

    /**
     *  获取返回的相册图片路径
     * @param context
     * @param intent
     * @return
     */
    public static String getPhotoPath(Context context,Intent intent){
        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.KITKAT){
          return   handleImageOnKitKat(context,intent);//4.4之后图片解析
        }else {
         return    handleImageBeforeKitKat(context,intent);//4.4之前图片解析
        }
    }
    /**
     * 4.4版本以下对返回的图片Uri的处理：
     * 就是从返回的Intent中取出图片Uri，直接显示就好
     * @param data 调用系统相册之后返回的Uri
     */
    private static String handleImageBeforeKitKat(Context context,Intent data) {
        Uri uri = data.getData();
        String imagePath = getImagePath(context,uri,null);
       return imagePath;
    }

    /**
     * 4.4版本以上对返回的图片Uri的处理：
     * 返回的Uri是经过封装的，要进行处理才能得到真实路径
     * @param data 调用系统相册之后返回的Uri
     */
    @TargetApi(19)
    private static String handleImageOnKitKat(Context context,Intent data) {
        String imagePath = null;
        Uri uri = data.getData();
        if (DocumentsContract.isDocumentUri(context, uri)) {
            //如果是document类型的Uri，则提供document id处理
            String docId = DocumentsContract.getDocumentId(uri);
            if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                String id = docId.split(":")[1];//解析出数字格式的id
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(context,MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
                imagePath = getImagePath(context,contentUri, null);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            //如果是content类型的uri，则进行普通处理
            imagePath = getImagePath(context,uri, null);
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            //如果是file类型的uri，则直接获取路径
            imagePath = uri.getPath();
        }
       return imagePath;
    }

    /**
     * 将Uri转化为路径
     * @param uri 要转化的Uri
     * @param selection 4.4之后需要解析Uri，因此需要该参数
     * @return 转化之后的路径
     */
    private static String getImagePath(Context context, Uri uri, String selection) {
        String path = null;
        Cursor cursor = context.getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    /**
     *  获取assets里的文件
     * @param context
     * @param fileName
     * @return
     */
    public static String getFromAssets(Context context,String fileName){
        try {
            InputStreamReader inputReader = new InputStreamReader(context.getResources().getAssets().open(fileName) );
            BufferedReader bufReader = new BufferedReader(inputReader);
            String line="";
            String Result="";
            while((line = bufReader.readLine()) != null)
                Result += line;
            return Result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }


    /**
     * 从raw里获取数据
     * @param context
     * @param resourceId
     * @return
     */
    public static String getFromRaw(Context context, int resourceId) {
        if( null == context || resourceId < 0 ){
            return null;
        }
        String result = null;
        try {
            InputStream inputStream = context.getResources().openRawResource( resourceId );
            // 获取文件的字节数
            int length = inputStream.available();
            // 创建byte数组
            byte[] buffer = new byte[length];
            // 将文件中的数据读到byte数组中
            inputStream.read(buffer);
            result = new String(buffer,"utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
